// pages/settlement/settlement.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        is_hide: true,
        is_show: "",
        total: 0,
        coupon: "未选择",
        note: "",
        coupon_id: "",
        coupon_amount: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.get_coupon_from_storage();
        var that = this;
        wx.getStorage({
            key: 'cartIDs',
            success: function (res) {
                var params = {};
                params['cartIDs'] = res.data;
                that.setData({
                    cartIDs: res.data,
                })
                that.settlement(params)
            }
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.switchTab({
            url: '../../pages/cart/cart',
        })
        wx.removeStorage({
            key: 'coupon_obj',
            success: function (res) {
            }
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    imageLoad: function (e) {

    },//获取地址
    setAddress: function () {
        var that = this;
        wx.getSetting({
            success: function (res) {
                if (res.authSetting['scope.address'] == false) {
                    wx.openSetting({
                        success: function (res) {
                            
                        },
                        fail: function (res) {

                        },
                        complete: function (res) {

                        }
                    })
                }
            }
        })
        wx.chooseAddress({
            success: function (res) {
                if (res.errMsg == "chooseAddress:ok") {
                    var userName = res.userName;
                    var address = res.provinceName + res.cityName + res.countyName + res.detailInfo;
                    var telNumber = res.telNumber;
                    that.setData({
                        consignee_name: userName,
                        consignee_address: address,
                        consignee_phone_number: telNumber,
                        is_hide: "",
                        is_show: true
                    })
                    var params = {};
                    params['member_id'] = that.data.member_id;
                    params['name'] = userName;
                    params['phone_number'] = telNumber;
                    params['address'] = address;
                    wx.request({
                        url: app.config() + 'order/updateMemberAddress',
                        data: params,
                        header: {
                            'content-type': 'application/json'
                        },
                        success: function (res) {

                        }
                    })
                }
            }
        })
    },
    settlement: function (params) {
        var that = this;
        wx.request({
            url: app.config() + 'order/goodsToGenerate',
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (res.data.status == 0) {
                    var goods = res.data.data.goods;
                    var member_id = res.data.data.memberAddress.member_id;
                    var consignee_address = res.data.data.memberAddress.consignee_address;
                    var consignee_name = res.data.data.memberAddress.consignee_name;
                    var consignee_phone_number = res.data.data.memberAddress.consignee_phone_number;
                    if (member_id && consignee_address && consignee_name && consignee_phone_number) {
                        that.setData({
                            consignee_name: consignee_name,
                            consignee_address: consignee_address,
                            consignee_phone_number: consignee_phone_number,
                            is_hide: "",
                            is_show: true
                        })
                    }
                    var total = 0;
                    var additional_money = 0;
                    var number = 0;
                    for (var i = 0; i < goods.length; i++) {
                        var sales_money = goods[i].sales_money;
                        var num = goods[i].number;
                        var front_pay = goods[i].front_pay;
                        if (front_pay != "全款支付") {
                            total += parseFloat(goods[i].front_pay) * num;
                            goods[i].front_pay = "订金支付￥" + goods[i].front_pay
                            that.setData({
                                whether_front_pay: 1//判断商品中是否有订金支付
                            })
                        } else {
                            total += parseFloat(sales_money) * num;
                        }
                        if (goods[i].type == "衬衣") {
                            additional_money += parseFloat(goods[i].additional_money) * num;//附加费用
                        }
                    }
                    // 优惠券金额
                    var coupon_amount = 0;
                    if (that.data.coupon != '未选择') {
                        coupon_amount = that.data.coupon.split("：")[1];
                    }
                    var watting_total_money = parseInt(total) + parseInt(additional_money) * 1 - coupon_amount;//待支付总金额
                    that.setData({
                        goodsList: goods,
                        total: total,
                        member_id: member_id,
                        additional_money: additional_money,
                        watting_total_money: watting_total_money,
                        coupon_amount: coupon_amount
                    })
                }
            }
        })
    },//立即支付
    to_pay_order: function (e) {
        var form_id = e.detail.formId;
        wx.showLoading({
            title: '加载中',
        })
        var that = this;
        var name = that.data.consignee_name;
        var address = that.data.consignee_address;
        var phone_number = that.data.consignee_phone_number;
        if (!name && !address && !phone_number) {
            wx.showToast({
                title: '请完善收货信息',
                icon: 'loading',
                duration: 1000
            })
            return;
        }
        var params = {};
        params['cartIDs'] = that.data.cartIDs;
        var coupon_id = that.data.coupon_id;
        if (coupon_id) {
            params['coupon_id'] = coupon_id;
        }
        var note = that.data.note;
        if (note) {
            params['note'] = note;
        }
        params["form_id"] = form_id;
        wx.request({
            url: app.config() + 'order/orderFromGenerate',
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                var order_id = res.data.data.order_id;
                wx.login({
                    success: function (res) {
                        var args = {};
                        args['code'] = res.code;
                        args['grant_type'] = "authorization_code";
                        wx.request({
                            url: app.config() + 'index/getXiaoToken',
                            data: args,
                            header: {
                                'content-type': 'application/json'
                            },
                            success: function (res) {
                                var open_id = res.data.data.openid;
                                var params = {};
                                params['open_id'] = open_id;
                                params['order_id'] = order_id;
                                wx.request({
                                    url: app.config() + 'order/xiaowxpay',
                                    data: params,
                                    header: {
                                        'content-type': 'application/json'
                                    },
                                    success: function (res) {
                                        wx.hideLoading();
                                        if (res.data.status == 0) {
                                            var timeStamp = res.data.data.timeStamp;//时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
                                            var nonceStr = res.data.data.nonceStr;//随机字符串，长度为32个字符以下
                                            var packages = res.data.data.package;
                                            var signType = res.data.data.signType;
                                            var paySign = res.data.data.paySign;
                                            wx.requestPayment({
                                                'timeStamp': timeStamp,
                                                'nonceStr': nonceStr,
                                                'package': packages,
                                                'signType': 'MD5',
                                                'paySign': paySign,
                                                'success': function (res) {
                                                    that.success_pay(order_id)
                                                },
                                                'fail': function (res) {
                                                    wx.showToast({
                                                        title: '支付失败',
                                                        image: "../../images/warning.png"
                                                    })
                                                    setTimeout(function () {
                                                        wx.navigateTo({
                                                            url: '../../pages/wattingPayment/wattingPayment',
                                                        })
                                                    }, 1000)

                                                },
                                                'complete': function (res) {
                                                    if (res.errMsg === "requestPayment:cancel") {
                                                        wx.showToast({
                                                            title: '支付失败',
                                                            image: "../../images/warning.png"
                                                        })
                                                        setTimeout(function () {
                                                            wx.navigateTo({
                                                                url: '../../pages/wattingPayment/wattingPayment',
                                                            })
                                                        }, 2000)
                                                    }
                                                    wx.removeStorage({
                                                        key: 'coupon_obj',
                                                        success: function (res) { },
                                                    })
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: res.data.message,
                                                image: "../../images/warning.png"
                                            })
                                        }

                                    }
                                })
                            }
                        })
                    }
                })
            }
        })
    },
    inputEvents: function (e) {
        this.setData({
            note: e.detail.value
        })

    },
    get_coupon_from_storage: function () {
        var that = this;
        wx.getStorage({
            key: 'coupon_obj',
            success: function (res) {
                var data = res.data;
                var coupon_id = data['coupon_id'];//优惠券id
                var coupon_amount = data['coupon_amount'];//优惠券金额
                if (coupon_id && coupon_amount) {
                    that.setData({
                        coupon: "已选择：" + coupon_amount,
                        coupon_id: coupon_id
                    })
                } else {
                    that.setData({
                        coupon: "未选择",
                        coupon_id: coupon_id
                    })
                }
            },
        })
    },//支付成功
    success_pay: function (order_id) {
        var params = {};
        params['order_id'] = order_id;
        wx.request({
            url: app.config() + "order/xiaoSuccessPay",
            data: params,
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                if (res.data.status == 0) {
                    wx.navigateTo({
                        url: '../../pages/successPay/successPay?order_id=' + order_id,
                    })
                }
            }

        })
    },
    customized: function (e) {
        var that = this;
        wx.showLoading({
            title: '加载中……',
        })
        var cart_id = e.currentTarget.dataset.cart_id;
        wx.navigateTo({
            url: '../../pages/customized/customized?id=' + cart_id,
        })
        setTimeout(function () {
            wx.hideLoading();
        })
    },//去优惠券列表
    to_coupon_list: function () {
        wx.showLoading({
            title: '加载中……',
        })
        setTimeout(function () {
            wx.hideLoading()
            wx.navigateTo({
                url: '../../pages/coupon/coupon?flag=order',
            })
        }, 200)

    }
})